module.exports = function(options){
    for (let key in options) this[key] = options[key]
    let Item = new a.Item()
    this.fetch = async function(url, options){
        options = options || {}
        options.headers = options.headers || {}
        if(this.PageLoading && this.PageLoading.open) {
            if(this.PageLoading.timers) {
                clearTimeout(this.PageLoading.timers)
            }else{
                this.PageLoading.open()
            }
        }
        options.headers.token = await this.getToken()
        // let rc = await (new a.Ajax(null,null,{ storage:{
        //     name:a.MD5(url + JSON.stringify({ ...options.body, _:'' } )),
        //     type:1
        // }, xhr:this.xhr,timeout:10 * 60 * 1000 })).fetch(url,options)
        let rc = await (new a.Ajax(null,null,{ xhr:this.xhr,timeout:10 * 60 * 1000 })).fetch(url,options)
        if(this.PageLoading && this.PageLoading.close) {
            this.PageLoading.timers = setTimeout(()=>{
                this.PageLoading.close()
            } ,300)
        }
        return typeof rc == 'string' ? JSON.parse(rc) : rc
    }
    let base64 = new a.Base64()
    this.getToken = async function() {
        if (this.token) return this.token
        this.token = a.Storage.get('token',1)
        if (this.token) return this.token
    }
    this.init = async function(dom){
        let iframes = (dom || document).querySelectorAll('iframe')
        for (let i = 0; i < iframes.length; i++) {
            let viewid = iframes[i].getAttribute('viewid')
            let params = iframes[i].getAttribute('params') || ''
            params = params.replace('token=','client_token=')
            if(viewid) {
                iframes[i].removeAttribute('viewid')
                iframes[i].removeAttribute('params')
                iframes[i].setAttribute('src', `${this.APIURL}/dataview?id=${viewid}&token=${await this.getToken()}&${params}`)
            }
        }
    }
    Item._push(async next => {
        await this.getToken()
        this.init()
        next()
    })
    Item._do()
    this.dataset = async function (id,params) {
        return new Promise(_next => {
            Item._push(async next => {
                next()
                _next(await this.fetch(`${this.APIURL}/v1/dataset`, { body:{ id,...params }}))
            })
        })
    }
    this.dataview = async function(id,params){
        return new Promise(_next => {
            Item._push(async next => {
                next()
                _next(await this.fetch(`${this.APIURL}/v1/dataview`, { body:{ id,...params }}))
            })
        })
    }
}